package com.lanou3g.com.study;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/5/17;
 * Otherwise, I don't know who created it either
 */

@WebServlet(name = "CookieServlet03",urlPatterns = "/cookie03")
public class CookieServlet03 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        response.setContentType("text/plain;charset=utf-8");
        // cookie可以设置 存活时间
        //URL编码 解决了 cookie不能存储中文的问题
        String val = URLEncoder.encode("中文","utf8");
        Cookie cookie = new Cookie("cookie03",val);
        // 存活时间的单位 是 秒
        /*
        maxAge: >0 表示cookie存活多少秒,到时间浏览器自动删除该
                cookie
        maxAge: <0 无论设置成多少,都表示 活到浏览器关闭
                默认值 就是-1
        maxAge: =0 表示 告诉浏览器 立即删除这个cookie
         */
        cookie.setMaxAge(20);
        response.addCookie(cookie);

        // 让cookie 可以在 各个二级域名之间共享
        //cookie.setDomain("baidu.com");
        /*
        www.baidu.com
        .com 顶级域名
        baidu.com 一级域名
        www.baidu.com 二级域名
        pan.baidu.com 二级域名
         */

        PrintWriter writer = response.getWriter();
        for (Cookie c : request.getCookies()) {
            String name = c.getName();
            String value = c.getValue();
            writer.println(name + "::" + value);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
